<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="研究方向" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门/研究方向"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="货物/服务名称" prop="goodsServiceName">
        <el-input
          v-model="queryParams.goodsServiceName"
          placeholder="请输入货物/服务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预估采购数量" prop="estimatedPurchaseQuantity">
        <el-input
          v-model="queryParams.estimatedPurchaseQuantity"
          placeholder="请输入预估采购数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预估采购金额" prop="estimatedPurchaseAmount">
        <el-input
          v-model="queryParams.estimatedPurchaseAmount"
          placeholder="请输入预估采购金额"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购方式" prop="procurementMethod">
        <el-input
          v-model="queryParams.procurementMethod"
          placeholder="请输入采购方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="报送日期">
        <el-date-picker
          v-model="daterangeSubmissionDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>    
      <el-form-item label="审批状态" prop="approveStatus">
       <el-select v-model="queryParams.approveStatus" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.yy_bip_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>

      <el-form-item label="采购论证状态" prop="procurementStatus">
        <el-select v-model="queryParams.procurementStatus" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.procurement_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>

      <el-form-item label="采购招标状态" prop="procurementBiddingStatus">
        <el-select v-model="queryParams.procurementBiddingStatus" placeholder="请选择审批状态" clearable>
                    <el-option
                      v-for="dict in dict.type.procurement_bidding_status"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    />
                  </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
         <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sci:purchaseRequirement:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sci:purchaseRequirement:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sci:purchaseRequirement:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sci:purchaseRequirement:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseRequirementList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="部门/研究方向" align="center" prop="departmentName" />
      <el-table-column label="申请人" align="center" prop="applicantName" />
      <el-table-column label="报送日期" align="center" prop="submissionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.submissionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购方式" align="center" prop="procurementMethod" />
      <el-table-column label="货物/服务名称" align="center" prop="goodsServiceName" />
      <el-table-column label="预估采购数量" align="center" prop="estimatedPurchaseQuantity" />
      <el-table-column label="预估采购金额" align="center" prop="estimatedPurchaseAmount" />
      <el-table-column label="审批状态" align="center" prop="approveStatus" >
         <template slot-scope="scope">
            <dict-tag :options="dict.type.yy_bip_status" :value="scope.row.approveStatus"/>
          </template>
      </el-table-column>
        <el-table-column label="采购论证状态" align="center" prop="procurementStatus">
            <template slot-scope="scope">
            <dict-tag :options="dict.type.procurement_status" :value="scope.row.procurementStatus"/>
          </template>
      </el-table-column>
      <el-table-column label="采购招标状态" align="center" prop="procurementBiddingStatus" >
          <template slot-scope="scope">
            <dict-tag :options="dict.type.procurement_bidding_status" :value="scope.row.procurementBiddingStatus"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['sci:purchaseRequirement:query']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sci:purchaseRequirement:edit']"
          >修改</el-button> -->
          
           <!-- 论证按钮（带条件控制） -->
        <el-popover
          placement="top"
          width="220"
          v-model="scope.row.reasoningVisible"
          :disabled="!isReasoningAllowed(scope.row)"
        >
          <p>确认要执行采购论证操作吗？</p>
          <div style="text-align: right; margin: 10px 0 0">
            <el-button type="primary" size="mini" @click="confirmReasoning(scope.row)">确定</el-button>
            <el-button size="mini" @click="scope.row.reasoningVisible = false">取消</el-button>
          </div>
          <el-button
            slot="reference"
            size="mini"
            type="text"
            icon="el-icon-document"
            :disabled="!isReasoningAllowed(scope.row)"
            v-hasPermi="['sci:purchaseRequirement:reasoning']"
          >论证</el-button>
        </el-popover>
        
        <!-- 招标按钮（带条件控制） -->
        <el-popover
          placement="top"
          width="220"
          v-model="scope.row.biddingVisible"
          :disabled="!isBiddingAllowed(scope.row)"
        >
          <p>确认要执行采购招标操作吗？</p>
          <div style="text-align: right; margin: 10px 0 0">
            <el-button type="primary" size="mini" @click="confirmBidding(scope.row)">确定</el-button>
            <el-button size="mini" @click="scope.row.biddingVisible = false">取消</el-button>
          </div>
          <el-button
            slot="reference"
            size="mini"
            type="text"
            icon="el-icon-shopping-cart-2"
            :disabled="!isBiddingAllowed(scope.row)"
            v-hasPermi="['sci:purchaseRequirement:inviteTenders']"
          >招标</el-button>
        </el-popover>

        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购需求申请单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="单据号" prop="documentNumber">
          <el-input v-model="form.documentNumber" placeholder="请输入单据号" />
        </el-form-item>
        <el-form-item label="单据日期" prop="documentDate">
          <el-input v-model="form.documentDate" placeholder="请输入单据日期" />
        </el-form-item>
        <el-form-item label="申请单位" prop="applicantOrgName">
          <el-input v-model="form.applicantOrgName" placeholder="请输入申请单位" />
        </el-form-item>
        <el-form-item label="部门/研究方向" prop="departmentName">
          <el-input v-model="form.departmentName" placeholder="请输入部门/研究方向" />
        </el-form-item>
        <el-form-item label="申请人" prop="applicantName">
          <el-input v-model="form.applicantName" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item l
        abel="报送日期" prop="submissionDate">
          <el-date-picker clearable
            v-model="form.submissionDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择报送日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请事由" prop="applicationReason">
          <el-input v-model="form.applicationReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="申请金额" prop="applicationAmount">
          <el-input v-model="form.applicationAmount" placeholder="请输入申请金额" />
        </el-form-item>
        <el-form-item label="采购方式" prop="procurementMethod">
          <el-input v-model="form.procurementMethod" placeholder="请输入采购方式" />
        </el-form-item>
        <el-form-item label="单一来源说明" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="服务编码" prop="serviceCode">
          <el-input v-model="form.serviceCode" placeholder="请输入服务编码" />
        </el-form-item>
        <el-form-item label="货物/服务名称" prop="goodsServiceName">
          <el-input v-model="form.goodsServiceName" placeholder="请输入货物/服务名称" />
        </el-form-item>
        <el-form-item label="规格、参数技术指标" prop="specifications">
          <el-input v-model="form.specifications" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="计量单位" prop="measurementUnit">
          <el-input v-model="form.measurementUnit" placeholder="请输入计量单位" />
        </el-form-item>
        <el-form-item label="需求时间" prop="requiredDate">
          <el-input v-model="form.requiredDate" placeholder="请输入需求时间" />
        </el-form-item>
        <el-form-item label="采购事项说明" prop="procurementDescription">
          <el-input v-model="form.procurementDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="资金来源" prop="fundingSource">
          <el-input v-model="form.fundingSource" placeholder="请输入资金来源" />
        </el-form-item>
        <el-form-item label="预估采购数量" prop="estimatedPurchaseQuantity">
          <el-input v-model="form.estimatedPurchaseQuantity" placeholder="请输入预估采购数量" />
        </el-form-item>
        <el-form-item label="预估采购金额" prop="estimatedPurchaseAmount">
          <el-input v-model="form.estimatedPurchaseAmount" placeholder="请输入预估采购金额" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

       <!-- 查看抽屉 -->
    <el-drawer
      title="采购需求详情"
      :visible.sync="drawer"
      size="50%"
      direction="rtl"
    >
     <!-- 自定义标题插槽 -->
  <div slot="title" class="drawer-title">
    <span>采购需求详情</span>
    <el-tag 
      :type="getStatusTagType(formView.approveStatus)"
      size="medium"
      style="margin-left: 10px;"
    >
      <dict-tag 
        :options="dict.type.yy_bip_status" 
        :value="formView.approveStatus"
      />
    </el-tag>
  </div>
      <!-- 第一部分 -->
      <el-card shadow="always" style="margin: 20px;">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="单据编号">{{ formView.documentNumber }}</el-descriptions-item>
          <el-descriptions-item label="单据日期">{{ formView.documentDate }}</el-descriptions-item>
          <el-descriptions-item label="申请单位">{{ formView.applicantOrgName }}</el-descriptions-item>
          <el-descriptions-item label="部门/研究方向">{{ formView.departmentName }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ formView.applicantName }}</el-descriptions-item>
          <el-descriptions-item label="报送日期">{{ parseTime(formView.submissionDate, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="申请事由">{{ formView.applicationReason }}</el-descriptions-item>
          <el-descriptions-item label="申请金额">{{ formView.applicationAmount }}</el-descriptions-item>
          <el-descriptions-item label="采购方式">{{ formView.procurementMethod }}</el-descriptions-item>
          <el-descriptions-item label="单一来源原因">{{ formView.notes }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 第二部分 - 修改为表格展示多行数据 -->
    <el-card shadow="always" style="margin: 20px;">
      <div class="card-title">详细信息</div> <!-- 自定义标题 -->
          <el-table 
            :data="detailList" 
            border 
            style="width: 100%; margin-top: 10px;"
            :show-header="true"
          >
            <el-table-column label="货物/服务名称" align="center" prop="goodsServiceName" />
            <el-table-column label="预采购数量" align="center" prop="estimatedPurchaseQuantity" />
            <el-table-column label="预估采购金额" align="center" prop="estimatedPurchaseAmount" />
            <el-table-column label="服务编码" align="center" prop="serviceCode" />
            <el-table-column label="规格、参数技术指标" align="center" prop="specifications" />
            <el-table-column label="计量单位" align="center" prop="measurementUnit" />
            <el-table-column label="需求时间" align="center" prop="requiredDate" />
            <el-table-column label="资金来源" align="center" prop="fundingSource" />
            <el-table-column label="采购事项说明" align="center" prop="procurementDescription" />
             <el-table-column label="采购论证状态" align="center" prop="procurementStatus" >
             <dict-tag :options="dict.type.procurement_status" :value="formView.procurementStatus"/>
             </el-table-column>
              <el-table-column label="采购招标状态" align="center" prop="procurementBiddingStatus" >
                <dict-tag :options="dict.type.procurement_status" :value="formView.procurementBiddingStatus"/>
              </el-table-column>
          </el-table>
       
    </el-card>
    </el-drawer>
  </div>
</template>

<script>
import { listPurchaseDetails,listPurchaseRequirement, getPurchaseRequirement, delPurchaseRequirement, addPurchaseRequirement, updatePurchaseRequirement } from "@/api/sci/purchaseRequirement";

export default {
  name: "PurchaseRequirement",
  dicts:['yy_bip_status','procurement_status','procurement_bidding_status'],
  data() {
    return {
     detailList: [], // 新增明细列表数据
      drawer: false, // 控制抽屉显示
      formView: {},   // 查看表单数据
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购需求申请单表格数据
      purchaseRequirementList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 预估采购金额时间范围
      daterangeSubmissionDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        approveStatus: null,
        departmentName: null,
        applicantName: null,
        submissionDate: null,
        procurementMethod: null,
        goodsServiceName: null,
        estimatedPurchaseQuantity: null,
        estimatedPurchaseAmount: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 检查是否允许论证
    isReasoningAllowed(row) {
      const amount = parseFloat(row.estimatedPurchaseAmount);
      return amount >= 20000 && 
             amount < 200000 && 
             row.procurementStatus !== 1; // 1表示已论证
    },
    
    // 检查是否允许招标
    isBiddingAllowed(row) {
      const amount = parseFloat(row.estimatedPurchaseAmount);
      return amount >= 200000 && 
             row.procurementBiddingStatus !== 1; // 1表示已招标
    },
    
    // 确认论证操作
    confirmReasoning(row) {
      row.reasoningVisible = false;
      this.updateProcurementStatus(row.id, 'procurementStatus', '1');
    },
    
    // 确认招标操作
    confirmBidding(row) {
      row.biddingVisible = false;
      this.updateProcurementStatus(row.id, 'procurementBiddingStatus', '1');
    },
    
    // 更新采购状态
    updateProcurementStatus(id, field, value) {
      const params = {
        id: id,
        [field]: value
      };
      
      updatePurchaseRequirement(params).then(response => {
        this.$modal.msgSuccess("操作成功");
        this.getList(); // 刷新数据
      }).catch(error => {
        this.$modal.msgError("操作失败");
      });
    },
    /** 查看按钮操作 */
   /** 查看按钮操作 - 修改为获取明细数据 */
    handleView(row) {
      const code = row.documentNumber;
      const id=row.id;
      // 获取主表数据
      // getPurchaseRequirement(id).then(response => {
      //   this.formView = response.data;
        
        // 获取明细数据
        listPurchaseDetails(row.documentNumber).then(detailResponse => {
          this.formView = detailResponse.data[0];
          this.detailList = detailResponse.data;
          this.drawer = true;
        }).catch(() => {
          this.detailList = [];
          this.drawer = true;
      //  });
      });
    },
    
    // 时间格式化方法
    parseTime(time, format = '{y}-{m}-{d}') {
      if (!time) return '';
      let date = new Date(time);
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds()
      };
      return format.replace(/{([ymdhisa])+}/g, (result, key) => {
        const value = formatObj[key];
        return value.toString().padStart(2, '0');
      });
    },
    /** 查询采购需求申请单列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeSubmissionDate && '' != this.daterangeSubmissionDate) {
        this.queryParams.params["beginSubmissionDate"] = this.daterangeSubmissionDate[0];
        this.queryParams.params["endSubmissionDate"] = this.daterangeSubmissionDate[1];
      }
      listPurchaseRequirement(this.queryParams).then(response => {
        this.purchaseRequirementList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        approveStatus: null,
        documentNumber: null,
        documentDate: null,
        applicantOrgName: null,
        departmentName: null,
        applicantName: null,
        submissionDate: null,
        applicationReason: null,
        applicationAmount: null,
        procurementMethod: null,
        notes: null,
        procurementType: null,
        serviceCode: null,
        goodsServiceName: null,
        specifications: null,
        measurementUnit: null,
        requiredDate: null,
        procurementDescription: null,
        fundingSource: null,
        estimatedPurchaseQuantity: null,
        estimatedPurchaseAmount: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeSubmissionDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加采购需求申请单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPurchaseRequirement(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改采购需求申请单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchaseRequirement(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPurchaseRequirement(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购需求申请单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchaseRequirement(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sci/purchaseRequirement/export', {
        ...this.queryParams
      }, `purchaseRequirement_${new Date().getTime()}.xlsx`)
    },
    // 根据状态值返回对应的标签类型
  getStatusTagType(status) {
    switch(status) {
      case 0: return 'info';    // 未提交
      case 3: return 'warning'; // 审批中
      case 1: return 'success'; // 审批通过
      default: return 'info';
    }
  },
  }
};
</script>

<style scoped>
.drawer-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}
/* 添加抽屉内容的样式 */
.el-drawer__body {
  padding: 0;
  overflow-y: auto;
}

.el-card {
  margin-bottom: 15px;
}

.el-descriptions__title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}
.el-descriptions-item.hidden-item {
  display: none;
}
.card-title{
   font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}
</style>

